package com.qc31.monitorlib.ui.line

import android.graphics.Color
import android.view.View
import androidx.fragment.app.activityViewModels
import com.github.mikephil.charting.components.LimitLine
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.qc31.baselib.base.LazyFragment
import com.qc31.baselib.utils.Language
import com.qc31.comlib.entity.HistoryLine
import com.qc31.monitorlib.chart.MPChartUtils
import com.qc31.monitorlib.R
import com.qc31.monitorlib.databinding.FragmentWholeBinding

/**
 *@Author Jasper
 *@Time   2020/8/12
 *@Desc   整体数据展示
 */
class WholeFragment : LazyFragment<FragmentWholeBinding>(FragmentWholeBinding::inflate) {

    private val mActivityVM by activityViewModels<LineInfoViewModel>()
    override fun initView(view: View) {
        binding.tvStartTime.isSelected= Language.instance.isEnglish()
        binding.tvEndTime.isSelected= Language.instance.isEnglish()
    }

    override fun initData() {
        MPChartUtils.configChart(binding.speedLineChart)
        mActivityVM.speed.observe(this) {
            val limit = LimitLine(it, getString(R.string.desc_history_speed_threshold))
            limit.lineWidth = 2f
            limit.textSize = 10f
            binding.speedLineChart.axisLeft.addLimitLine(limit)
        }
        mActivityVM.data.observe(this) {
            it?.countData?.run {
                binding.tvWholeRunTime.text = moveLong
                binding.tvWholeStopTime.text = stopLong
                binding.tvWholeRunMile.text =
                    String.format("%s %s", mile, getString(R.string.unit_mile))
                binding.tvWholeMaxSpeed.text =
                    String.format("%s %s", maxSpeed, getString(R.string.unit_speed))
                binding.tvWholeAverSpeed.text =
                    String.format("%s %s", avgSpeed, getString(R.string.unit_speed))
            }
            binding.tvStartTime.text = "${getString(R.string.desc_start)}:${it.locations[0].time}"
            binding.tvEndTime.text = "${getString(R.string.desc_end)}:${it.locations.last().time}"
            binding.tvWholeLocatPoint.text = "${it.locations.size} ${getString(R.string.desc_unit_num)}"

            binding.tvWholeStartAddr.text = it.locations[0].addr
            binding.tvWholeEndAddr.text = it.locations.last().addr
            initChart(it.locations)
        }


    }

    override fun initEvent() {

    }

    private fun initChart(list: List<HistoryLine.Location>?) {
        if (list == null) return
        val entities = ArrayList<Entry>()
        for ((index, entity) in list.withIndex()) {
            entities.add(Entry(index.toFloat(), entity.speed.toFloat()))
        }

        binding.speedLineChart.data =
            LineData(MPChartUtils.getLineData(entities, Color.parseColor("#3791E9")))
    }
}